<?php
class crm_rpc_gift extends crm_rpc_request{

    //获取crm赠品规则
    /*
    shop_id        店铺ID
    order_bn       订单号
    buyer_nick     买家昵称
    receiver_name  收货人姓名
    mobile         联系电话（手机）
    */
    public function getGiftRule($data){
       $res = array('result'=>'fail','data'=>array(),'msg'=>'获取失败');

       $api_name = 'store.gift.rule.get';
       
       $Oshop = app::get('ome')->model('shop');
       $shopdata = $Oshop->getRow(array('shop_id'=>$data['shop_id']),'node_id,name');

//       $params = array(
//           'buyer_nick'=>$data['buyer_nick'],
//           'receiver_name'=>$data['receiver_name'],
//           'mobile'=>$data['mobile'],
//           'unique_node'=>$shopdata['node_id'],
//       );

       $params = array(
           'buyer_nick' => $data['buyer_nick'],
           'receiver_name'=> $data['receiver_name'],
           'mobile' => $data['mobile'],
           'tel' => $data['tel'],
           'shop_id' => $data['shop_id'],
           'unique_node' => $shopdata['node_id'],
           'shop_name' => $shopdata['name'],
           'order_bn' => $data['order_bn'],
           'province' => $data['province'],
           'city' => $data['city'],
           'district' => $data['district'],
           'total_amount' => $data['total_amount'],
           'payed' => $data['payed'],
           'createtime' => $data['createtime'],
           'pay_time' => $data['pay_time'],
           'is_cod' => $data['is_cod'],
           'items' => is_array($data['items']) ? json_encode($data['items']) : $data['items'],
           'addon' => '',
           'is_send_gift' => $data['is_send_gift'],#强制重新请求的标示
       );
       $write_log = array(
           'class'=>__CLASS__,
           'method'=>__METHOD__,
           'order_bn'=>$data['order_bn'],
       );

       $result = $this->call('store.gift.rule.get','获取CRM赠品规则',$params,10,$write_log);

       return $result;
    }

    #发送CRM赠品日志
    public function getGiftRuleLog($data) {
        $res = array('result'=>'fail','data'=>array(),'msg'=>'发送失败');
        $api_name = 'store.gift.rule.get';
        $Oshop = app::get('ome')->model('shop');
        $shopdata = $Oshop->getRow(array('shop_id'=>$data['shop_id']),'node_id,name');
        $addon = array(
            'func' => 'log',
            'params' => $data['addon'],
        );
        $params = array(
            'buyer_nick' => $data['buyer_nick'],
            'receiver_name' => $data['receiver_name'],
            'mobile' => $data['mobile'],
            'tel' => $data['tel'],
            'shop_id' => $data['shop_id'],
            'unique_node' => $shopdata['node_id'],
            'shop_name' => $shopdata['name'],
            'order_bn' => $data['order_bn'],
            'province' => $data['province'],
            'city' => $data['city'],
            'district' => $data['district'],
            'total_amount' => $data['total_amount'],
            'payed' => $data['payed'],
            'is_cod' => $data['is_cod'],
            'items' => '',
            'addon' => json_encode($addon),
        );
        $write_log = array(
            'class' => __CLASS__,
            'method' => __METHOD__,
            'order_bn' => $data['order_bn'],
        );
        $result = $this->call('store.gift.rule.get', '发送CRM赠品日志', $params, 10, $write_log);
        return $result;
    }

    /**
     * 返回数据格式化
     * @param $data
     * @return array
     */
    function getFormatRst($data){
        $res = array('result'=>'fail','msg'=>'','data'=>array());

        $rst = $this->getLocalGiftRule($data);

        if(isset($rst['err'])){
            $res['msg'] = $rst['msg'];
            return $res;
        } else {
            $res['result'] = 'succ';
            $res['msg'] = $rst['msg'];
            $res['data'] = $rst;
            return $res;
        }
    }

    /**
     * 格式化参数 (废弃)
     */
    private function formatParams($data){

        $Oshop = app::get('ome')->model('shop');
        $shopdata = $Oshop->getRow(array('shop_id'=>$data['shop_id']),'node_id,name');

        $params = array(
            'buyer_nick' => $data['buyer_nick'],
            'receiver_name'=> $data['receiver_name'],
            'mobile' => $data['mobile'],
            'tel' => $data['tel'],
            'shop_id' => $data['shop_id'],
            'unique_node' => $shopdata['node_id'],
            'shop_name' => $shopdata['name'],
            'order_bn' => $data['order_bn'],
            'province' => $data['province'],
            'city' => $data['city'],
            'district' => $data['district'],
            'total_amount' => $data['total_amount'],
            'payed' => $data['payed'],
            'createtime' => $data['createtime'],
            'pay_time' => $data['pay_time'],
            'is_cod' => $data['is_cod'],
            'items' => is_array($data['items']) ? json_encode($data['items']) : $data['items'],
            'addon' => '',
            'is_send_gift' => $data['is_send_gift'],#强制重新请求的标示
        );

        return $params;
    }

    /**
     * 获取erp的赠品规则
     * @param $data
     * @return array
     */
    public function getLocalGiftRule($sdf){
        //获取前端店铺名和node_id
        $Oshop = app::get('ome')->model('shop');
        $shopdata = $Oshop->getRow(array('shop_id'=>$sdf['shop_id']),'node_id,name');
        $sdf['unique_node'] = $shopdata['node_id'];
        $sdf['shop_name'] = $shopdata['name'];
        
        //匹配规则前先判断是否有这三种错误 直接返回
        if(intval($sdf['is_cod']) == 1 || $sdf['pay_status'] != '1'){
            return array('err' => 1, 'msg' => '不处理货到付款和未付款订单');
        }
        if(!$sdf['buyer_nick'] && !$sdf['receiver_name']){
            return array('err' => 1, 'msg' => '买家帐号或收货人不能同时为空');
        }
        //这里is_send_gift都是0 process时$type默认给false
        if(intval($sdf['is_send_gift']) == 0){
            //查询赠品日志，已经送过的订单号不送第二次
            $rs = app::get('ome')->model('gift_logs')->dump(array('order_bn'=>$sdf['order_bn'],'shop_id'=>$sdf['shop_id']), 'id');
            if($rs){
                return array('err' => 1, 'msg' => '订单号'.$sdf['order_bn'].'不能重复赠送');
            }
        }

        //按优先级和主键 查询是否存在有效规则 新的能用的规则rule_type不为空 设置过类型是店铺级或者商品级的
        $sql = "select * from sdb_ome_gift_rule where status = '1' and rule_type is not null order by priority DESC,id DESC";
        $data = $Oshop->db->select($sql);
        
        if(!empty($data)){
            //同时获取店铺级和商品级的数组
            $rule_shop_level = array();
            $rule_good_level = array();
            foreach ($data as $var_data){
                if($var_data["rule_type"] == "shopLevel"){
                    $rule_shop_level[] = $var_data;
                }
                if($var_data["rule_type"] == "goodLevel"){
                    $rule_good_level[] = $var_data;
                }
            }
            
            $gift_ids = '0'; //赠品ID
            $gift_num = '0'; //赠品数量
            $gift_send_log = array(); //记录赠品发送日志
            $reason = ''; //不符合规则的原因
            //$index_flag = 1; // 标记是第几条规则
            $last_exclude_flag = "";//是否排他 1排他 2不排他
            
            if(!empty($rule_shop_level)){
                //先走店铺级规则 再走商品级规则
                $rs_gift_info = $this->getGiftInfo($rule_shop_level,$sdf,$gift_ids,$gift_num,$gift_send_log,$reason,$last_exclude_flag);

                if( $last_exclude_flag == 1 && $rs_gift_info["gift_num"] && $rs_gift_info["gift_ids"]){
                    // 如果第一条店铺规则满足且排他,则忽略后续商品级规则
                } else {

                    $rs_gift_info = $this->getGiftInfo($rule_good_level,$sdf,$rs_gift_info["gift_ids"],$rs_gift_info["gift_num"],$rs_gift_info["gift_send_log"],$rs_gift_info["reason"],$last_exclude_flag);
                }
            }else{
                //没有店铺级规则 直接走商品级规则
                if(!empty($rule_good_level)){
                    $rs_gift_info = $this->getGiftInfo($rule_good_level,$sdf,$gift_ids,$gift_num,$gift_send_log,$reason,$last_exclude_flag);
                }
            }

            //根据规则获取赠品信息过程中 如有reason并且没有匹配到赠品规则 直接返回
            if($rs_gift_info["reason"] && $rs_gift_info["gift_ids"] == "0"){
                return array('msg' => $rs_gift_info["reason"]);
            }

            //如果符合条件，判断是否有赠品库存，添加赠送日志
            if($rs_gift_info["gift_ids"] && $rs_gift_info["gift_ids"] != '0'){
                //获取每个赠品id对应的数量 
                $gift_id_arr = explode(',', $rs_gift_info["gift_ids"]);
                $gift_num_arr = explode(',', $rs_gift_info["gift_num"]);
                //移除之前获取赠品信息时的无用数据
                if(isset($gift_id_arr[0]) && intval($gift_id_arr[0]) == 0){
                    unset($gift_id_arr[0]);unset($gift_num_arr[0]);
                }
                foreach($gift_id_arr as $k=>$v){
                    $gift_id_num[$v] += intval($gift_num_arr[$k]);
                }
                
                $err_msg = '';
                $rs = app::get('crm')->model('gift')->getList('gift_id,gift_bn,gift_name,gift_num,giftset,product_id',array('gift_id'=>$gift_id_arr));
                $gift_bns = array();
                $gifts = array();

                foreach($rs as $v){

                    $gift_num = $gift_id_num[$v['gift_id']];
                    $left_num = $v['gift_num']-$gift_num;
                    //跳过当前赠品库存小于等于0的 或者 是剩余库存小于0的
                    //不设置赠品数量时不用判断当前数量是否够
                    $sqlstr = '';
                    if(($v['gift_num'] <= 0 || $left_num < 0) && $v['giftset'] == '0') {
                        $err_msg .= $v['gift_bn'].'库存不足;';

                        continue;
                    }
                    if($v['giftset'] == '2'){//根据库存数量
                        //gift_bn
                        $stockLib = kernel::single('material_sales_material_stock');
                        $store = $stockLib->getSalesMStockById($v['product_id']);
                        if($store<$gift_num){
                            $err_msg .= $v['gift_bn'].'可用库存不足;';

                            continue;
                        }
                    }

                    if($v['giftset'] == '0'){
                        $sqlstr=',gift_num=gift_num-'.$gift_num;
                    }
                    $rs_gifts[$v['gift_id']] = $v;
                    $gift_bns[] = $v['gift_bn'];
                    $gifts[$v['gift_bn']] = $gift_num;
                    //扣减库存
                    $sql = "update sdb_crm_gift set send_num=send_num+".$gift_num.$sqlstr." where gift_id=".$v['gift_id'];

                    $Oshop->db->exec($sql);
                }

                //记录赠品发送日志
                $create_time = time();$log_arr=array();
                //$m_gift_logs = app::get('ome')->model('gift_logs');
                foreach($rs_gift_info["gift_send_log"] as $v){
                    foreach($v['gift_ids'] as $kk=>$vv){
                        //跳过库存为 0 的赠品
                        if(!isset($rs_gifts[$vv])) {
                            continue;
                        }
                        $md5_key = md5($sdf['order_bn'].$rs_gifts[$vv]['gift_bn'].$v['gift_rule_id'].$create_time);
                        $log_arr[] = array(
                            'order_source'=>$sdf['shop_name'],
                            'order_bn'=>$sdf['order_bn'],
                            'buyer_account'=>$sdf['buyer_nick'],
                            'shop_id'=>$sdf['shop_id'],
                            'paid_amount'=>floatval($sdf['payed']),
                            'gift_num'=>$v['gift_num'][$kk],
                            'gift_rule_id'=>$v['gift_rule_id'],
                            'gift_bn'=>$rs_gifts[$vv]['gift_bn'],
                            'gift_name'=>$rs_gifts[$vv]['gift_name'],
                            'create_time'=>$create_time,
                            'md5_key'=>$md5_key,
                            'status'=>0,
                        );
                        //$m_gift_logs->save($log_arr);

                    }
                }

                //如果有报错误跳过信息 并且赠品数组是空
                if($err_msg && !$gifts){
                    return array('msg' => $err_msg);
                }
                
                //返回有效的赠品数据
                $return = array(
                    'order_bn'=>$sdf['order_bn'],
                    'gifts'=>$gifts,
                    'gift_bn'=>implode(',', $gift_bns),
                    'source'    =>  'local',
                    'log_arr'   =>  $log_arr,
                );
                if($err_msg){
                    $return['err_msg'] = $err_msg;
                }
                return $return;
                
            }
        } else {
            //没有有效的规则      
            return array('msg' => '不存在有效的促销规则，赠品获取失败');
        }

    }
    
    //检测是否符合赠送条件 店铺级规则和商品级规则共用
    private function getGiftInfo($rules,$sdf,$gift_ids,$gift_num,$gift_send_log,$reason,&$last_exclude_flag){
        $Oshop = app::get('ome')->model('shop');
        //还没有匹配到规则 获取到赠品信息
        $get_info_action = false;
        
        //循环匹配规则
        foreach($rules as $rule){
            if(!empty($last_exclude_flag)){
                if($last_exclude_flag == 1){
                    break;
                } else {
                    if($rule['is_exclude'] == 1){
                        continue;
                    }
                }
            }
            //检测时间有效期
            if($rule['time_type']=='createtime'){
                $createtime = intval($sdf['createtime']);
                if($createtime>$rule['end_time'] or $createtime<$rule['start_time']) {
                    $reason = '不符合选择的时间类型：订单创建时间的起止时间范围';
                    continue;
                }
            }elseif($rule['time_type']=='pay_time'){
                $pay_time = intval($sdf['pay_time']);
                if($pay_time>$rule['end_time'] or $pay_time<$rule['start_time']){
                    $reason = '不符合选择的时间类型：订单付款时间的起止时间范围';
                    continue;
                }
            }else{
                $time = time();
                if($time>$rule['end_time'] or $time<$rule['start_time']){
                    $reason = '不符合选择的时间类型：订单处理时间的起止时间范围';
                    continue;
                }
            }
        
            //赠品判断条件
            $rule['filter_arr'] = json_decode($rule['filter_arr'], true);
        
            //勾选的前端店铺 不勾选就是全选
            if($rule['shop_ids']){
                $rule['shop_ids'] = explode(',', $rule['shop_ids']);
            }
        
            if(!$rule['gift_ids']){
                $reason = '没有设定赠品';
                continue;
            }elseif($rule['shop_ids'] && !in_array($sdf['shop_id'], $rule['shop_ids'])){
                $reason = '不符合指定店铺';
                continue;
            }
        
            if($rule['filter_arr']['province']){
                if( ! $sdf['province'] or ! in_array($sdf['province'], $rule['filter_arr']['province'])){
                    $reason = '不符合指定收货区域';
                    continue;
                }
            }

            //订单类型过滤
            if($rule['filter_arr']['order_type']){
                $normal_selected = false;
                $presale_selected = false;
                foreach ($rule['filter_arr']['order_type'] as $order_t){
                    if ($order_t == "normal"){
                        $normal_selected = true;
                    }
                    if($order_t == "presale"){
                        $presale_selected = true;
                    }
                }
                //$rule['filter_arr']['order_type']普通订单normal和预售订单presale都选的情况下认为是全部订单 不考虑此条件
                if($normal_selected && $presale_selected){
                }else{
                    if(!in_array($sdf['order_type'], $rule['filter_arr']['order_type'])){
                        $reason = '不符合指定订单类型';
                        continue;
                    }
                }
            }
        
            if($rule['filter_arr']['order_amount']['type']==1){
                $payed = floatval($sdf['payed']);
                if($rule['filter_arr']['order_amount']['sign']=='bthan'){
                    if($payed<$rule['filter_arr']['order_amount']['max_num']){
                        $reason = '不满足最低付款';
                        continue;
                    }
                }else{
                    if($payed<$rule['filter_arr']['order_amount']['min_num'] or $payed>$rule['filter_arr']['order_amount']['max_num']){
                        $reason = '不满足付款区间';
                        continue;
                    }
                }
            }
        
            //限量赠送
            if($rule['filter_arr']['buy_goods']['limit_type']==1){
                //判断已经送出的订单数
                $sql = "select count(distinct order_bn) as total_orders from sdb_ome_gift_logs where gift_rule_id=".$rule['id']." ";
                $rs_temp = $Oshop->db->selectRow($sql);
                if($rs_temp) {
                    if($rs_temp['total_orders'] >= $rule['filter_arr']['buy_goods']['limit_orders']){
                        $reason = '超过送出数量限制';
                        continue;
                    }
                }
            }
        
            $has_buy = false;
            //$item_nums = $this->get_buy_goods_num($rule, $sdf['items'], $has_buy);
            $item_nums = $this->get_buy_goods_num($rule, $sdf['objects'], $has_buy);
            if($rule['filter_arr']['buy_goods']['count_type'] == 'paid'){
                $item_nums = floatval($sdf['payed']);
            }
        
            if($has_buy == false){
                $reason = '不符合指定商品购买条件';
                continue;
            }
            
            //计算赠品数量
            if($item_nums>0 && $rule['filter_arr']['buy_goods']['num_rule']=='auto'){
                $ratio = intval($item_nums/$rule['filter_arr']['buy_goods']['per_num']);
                $suite = $rule['filter_arr']['buy_goods']['send_suite']*$ratio;
                $suite = min($suite, $rule['filter_arr']['buy_goods']['max_send_suite']);
                if($suite >= 1){
                    //数量倍数
                    $temp_arr = explode(',', $rule['gift_num']);
                    foreach($temp_arr as $k=>$v){
                        $temp_arr[$k] = $v * $suite;
                    }
                    $temp_arr = implode(',', $temp_arr);
                }elseif($suite == 0){
                    //数量不符合要求
                    $reason = '不符合商品数量购买条件';
                    continue;
                }
                $last_exclude_flag = $rule["is_exclude"]; //是否排他 1排他 2不排他
                $gift_ids .= ','.$rule['gift_ids'];
                $gift_num .= ','.$temp_arr;
                $gift_send_log[] = array(
                        'gift_rule_id' => $rule['id'],
                        'gift_ids' => explode(',', $rule['gift_ids']),
                        'gift_num' => explode(',', $temp_arr)
                );
            }elseif($item_nums>0){
                if($rule['filter_arr']['buy_goods']['rules_sign']=='nequal'){
                    if($item_nums!=$rule['filter_arr']['buy_goods']['min_num']){
                        $reason = '不等于指定数量';
                        continue;
                    }
                }elseif($rule['filter_arr']['buy_goods']['rules_sign']=='between'){
                    if($item_nums<$rule['filter_arr']['buy_goods']['min_num'] or $item_nums>=$rule['filter_arr']['buy_goods']['max_num']){
                        $reason = '不在数量范围内';
                        continue;
                    }
                }else{
                    if($item_nums<$rule['filter_arr']['buy_goods']['min_num']){
                        $reason = '小于指定数量';
                        continue;
                    }
                }
                $last_exclude_flag = $rule["is_exclude"]; //是否排他 1排他 2不排他
                $gift_ids .= ','.$rule['gift_ids'];
                $gift_num .= ','.$rule['gift_num'];
                $gift_send_log[] = array(
                        'gift_rule_id' => $rule['id'],
                        'gift_ids' => explode(',', $rule['gift_ids']),
                        'gift_num' => explode(',', $rule['gift_num'])
                );
            }


        }
        
        return array(
            //"index_flag" => $index_flag,
            //"is_exclude" => $is_exclude,
            "gift_ids" => $gift_ids,
            "gift_num" => $gift_num,
            "gift_send_log" => $gift_send_log,
            "reason" => $reason,
        );
        
    }
    
    /**
     * @param $rule
     * @param $order_obj
     * @param $has_buy
     * @return int|mixed
     */
    public function get_buy_goods_num($rule, $order_obj, &$has_buy){
        $item_nums = 0;
        $item_num_arr = array();
        $item_bns = array();
        $buy_goods_bns = $rule['filter_arr']['buy_goods']['goods_bn'];
        $count_type = $rule['filter_arr']['buy_goods']['count_type'];

        if(!is_array($buy_goods_bns)){
            $buy_goods_bns = array($buy_goods_bns);
        }

        // 清理空数据
        $buy_goods_bns = $this->clear_value($buy_goods_bns);

        foreach($order_obj as $item){

            if($rule['filter_arr']['buy_goods']['type'] == 1){
                if($rule['filter_arr']['buy_goods']['buy_type'] == 'all'){
                    //购买了全部指定商品
                    if( ! in_array($item['bn'], $item_bns)) $item_bns[] = $item['bn'];
                    if(in_array($item['bn'], $buy_goods_bns)){
                        $item_num_arr[$item['bn']] = intval($item_num_arr[$item['bn']]) + $item['nums'];
                        unset($buy_goods_bns[array_search($item['bn'], $buy_goods_bns)]);
                    }
                }elseif($rule['filter_arr']['buy_goods']['buy_type'] == 'none'){
                    //排除购买的指定商品
                    if( ! in_array($item['bn'], $buy_goods_bns)){
                        $item_nums += $item['nums'];
                        if( ! in_array($item['bn'], $item_bns)) $item_bns[] = $item['bn'];
                        $has_buy = true;
                    }
                }else{
                    //购买了任意一个指定商品
                    if(in_array($item['bn'], $buy_goods_bns)){
                        $item_nums += $item['nums'];
                        if( ! in_array($item['bn'], $item_bns)) $item_bns[] = $item['bn'];
                        $has_buy = true;
                    }
                }
            } else {
                $item_nums += $item['nums'];
                $item_num_arr[$item['bn']] = intval($item_num_arr[$item['bn']]) + $item['nums'];
                $has_buy = true;
            }
        }

        //购买了全部指定商品，数量以最少的为准
        if($rule['filter_arr']['buy_goods']['type'] == 1){
            if($rule['filter_arr']['buy_goods']['buy_type'] == 'all'){
                if( ! $buy_goods_bns){
                    $item_nums = min($item_num_arr);
                    $has_buy = true;
                }
            }
        }

        if($count_type == 'sku' && $has_buy === true){
            $item_nums = count($item_bns);
        }

        return $item_nums;

    }

    //删除数组里的空元素
    public function clear_value($arr)
    {
        foreach($arr as $k=>$v){
            if(is_array($v)){
                $arr[$k] = $this->clear_value($v);
            }else{
                //检测邮政编码格式
                if($k === 'zip' && !preg_match("/^(\d){5,6}$/", $v)){
                    unset($arr[$k]);
                }

                if( ! $v) unset($arr[$k]);
            }
        }
        return $arr;
    }


    public function saveGiftLog($logs){
        $m_gift_logs = app::get('ome')->model('gift_logs');
        if($logs){
            foreach ($logs as $log){
                $m_gift_logs->save($log);
            }
        }
    }

}